import React, { PureComponent } from 'react';
import { Button, Form,message, DatePicker } from 'antd';
import Ellipsis from '@/components/Ellipsis';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import PateoTable from '@/common/PateoTable/PateoTable';
import PateoAuthButtons from '@/common/PateoAuthButtons/PateoAuthButtons';
import moment from "moment";
import WheelPathMapModal from "../../modals/wheelPathMapModal"

@connect(state => ({
  alarm: state.alarm,
}))
// @Form.create()
export default class WheelPathTable extends PureComponent {
  static contextTypes = {
    authButton: PropTypes.array,
    dicData: PropTypes.array,
  };
  state={
    listData: [],
    mapVisible: false,
    mapData: [],
  };
  componentDidMount() {
    const { dispatch, vin } = this.props;
    dispatch({
      type:"alarm/fetch",
      payload: { url:'/hmCommon/getHMTSPDeviceByVin', vin, date: moment().format("YYYY-MM-DD") },
      callback: response =>{
        if(response.statusCode === "0" &&  response.data){
          this.setState({ listData: response.data })
        }
      }
    });
  }
  onChange = (moment) =>{
    const { dispatch, vin } = this.props;
    dispatch({
      type:"alarm/fetch",
      payload: { url:'/hmCommon/getHMTSPDeviceByVin', vin, date:moment.format("YYYY-MM-DD") },
      callback: response =>{
        if(response.statusCode === "0" && response.data){
          this.setState({ listData: response.data })
        } else {
          this.setState({ listData: [] })
        }
      }
    });
  };
  handleOpenMap = (record) =>{
    const { dispatch } = this.props;
    dispatch({
      type:"alarm/fetch",
      payload: { url:'/hmCommon/getHMTSPPoint', vin: record.vin, starttime: record.collectionTimeL, endtime: record.e_collectionTimeL },
      callback: response =>{
          if(response.statusCode === '0'){
            // 会同时出现data为null和[]的情况  轨迹点少于2个点或者全是重复点会使地图展示出现异常
            if(response.data && response.data.length > 1){
              const lon = response.data[0].lon;
              const lat = response.data[0].lat;
              const lonData = response.data.filter(item => item.lon !== lon );
              const latData = response.data.filter(item => item.lat !== lat );
              if(lonData.length > 1 || latData.length > 1 ){
                this.setState({ mapVisible: true, mapData: response.data });
                //this.map.handleSetTimeOut();
                this.map.handleSetInterval(response.data);
              } else {
                message.info("轨迹点重复");
              }
            } else {
              message.info("当前记录没有行车轨迹")
            }
          } else {
            message.error(response.statusMessage);
          }
      }
    })
  };
  render() {
    const { alarm: { loading }, dispatch } = this.props;
    const { listData, mapVisible, mapData } = this.state;
    const columns = [
      {
        title: '行程开始时间',
        dataIndex: 'collectionTime',
        width:"10%",
      }, {
        title: '行程结束时间',
        dataIndex: 'e_collectionTime',
        width:"10%",
      }, {
        title: '行程时间',
        dataIndex: 'eachTime',
      }, {
        title: '最高时速',
        dataIndex: 'maxSpeed',
        width:"8%",
      },{
        title: '平均时速',
        dataIndex: 'avgSpeed',
        width:"8%",
      },{
        title: '单次里程（KM）',
        dataIndex: 'eachMile',
        width:"8%",
      }, {
        title: '单次油耗（L）',
        dataIndex: 'eFule',
        width:"8%",
      }, {
        title: '起始地点',
        dataIndex: 'startPointName',
        width:"15%",
        render:text => <Ellipsis length={16} tooltip>{text}</Ellipsis>
      }, {
        title: '停止地点',
        dataIndex: 'endPointName',
        width:"15%",
        render:text => <Ellipsis length={16} tooltip>{text}</Ellipsis>
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 150,
        fixed: "right",
        render: (text, record) => {
          const btns = [
            {
              title: '在地图中查看',
              key: 'map',
              onConfirm: () => {
               this.handleOpenMap(record);
              },
            }];
          return <PateoAuthButtons authStr="alarmRules" btns={btns} />;
        },
      }
    ];
    const tableProps={
      columns,
      dataSource:listData,
      loading:loading,
      rowKey:record =>record.sid,
      pagination:false,
      scroll:{ x: "160%",  y: 400 }
    };
    return (
      <div>
        <div style={{ marginBottom: 12 }}>
          <span>选择日期：</span>
          <DatePicker
            defaultValue={moment()}
            format={"YYYY-MM-DD"}
            onChange={this.onChange}
            allowClear={false}
          />
        </div>
        <PateoTable
          tableProps={tableProps}
          dispatch={dispatch}
        />
        <WheelPathMapModal
          onRef = { ref => this.map = ref }
          changeVisible={() => this.setState({ mapVisible: false, mapData:[]})}
          visible={mapVisible}
          mapData={mapData}
        />
      </div>
    );
  }
}
